package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.ygqh.baby.ao.CouponStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.PromotionType;
import com.ygqh.baby.ao.SalesPlatform;
import com.ygqh.baby.handler.ShoppingCarHandler;
import com.ygqh.baby.model.BaseSkuInfo;
import com.ygqh.baby.model.CarPricesResult;
import com.ygqh.baby.model.YgCouponModel;
import com.ygqh.baby.model.YgShoppingCarModel;
import com.ygqh.baby.po.YgSku;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 优惠卷
 *
 * @author guohao
 * @date 2018-12-13
 */
@Controller
@RequestMapping("/mobile/coupon")
public class YgCouponV2Controller extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private YgCouponService couponService;
    @Autowired
    private YgOrderService orderService;
    @Autowired
    private YgUserService ygUserService;
    @Autowired
    private YgShoppingCarService ygShoppingCarService;
    @Autowired
    private YgPublishService ygPublishService;
    @Autowired
    private YgCouponDetailService couponDetailService;
    @Autowired
    private YgBmdismService ygBmdismService;
    @Autowired
    private YgSkuService skuService;
    @Autowired
    private DocumentConstant documentConstant;
    @Autowired
    private ShoppingCarHandler shoppingCarHandler;

    @Autowired
    private WxMpMessageService wxMpMessageService;
    private final SalesPlatform salesPlatform = SalesPlatform.Yiigoo;

    /**
     * 获取优惠卷 及满减金额，运费的接口
     *
     * @param couponDetailId
     * @param productPrice
     * @param callback
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "findCouponForPay", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findCouponForPay(@RequestParam(defaultValue = "false") Boolean distribution, Long couponDetailId, BigDecimal productPrice,
                                        String formId, String callback) {
        if (couponDetailId == -1L) {
            couponDetailId = null;
        }
        YgUser currentUser = SessionUtil.getCurrentUser();
        List<YgShoppingCarModel> carModelList = ygShoppingCarService.findIsCheck(currentUser.getId(), distribution);
        CarPricesResult carPrices = shoppingCarHandler.getCarPrices(carModelList, formId, couponDetailId, SalesPlatform.Yiigoo);
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, carPrices));
    }


    /**
     * 结算页 获取优惠卷列表
     *
     * @param cStatus
     * @param productPrice
     * @param callback
     * @return
     */
    @SuppressWarnings({"unchecked"})
    @RequestMapping(value = "findCouponListForPay", method = RequestMethod.GET)
    @ResponseBody
    public JSONPObject findCouponListForPay(@RequestParam(defaultValue = "false") Boolean distribution,
                                            @RequestParam CouponStatus cStatus, String productIds, String formId,
                                            Boolean filterJiajiaGou, @RequestParam String callback) {
        JSONPObject json;
        YgUser user = SessionUtil.getCurrentUser();
        List<YgShoppingCarModel> carList;
        if (filterJiajiaGou != null && !filterJiajiaGou) {
            // 过滤加价购商品（即不进购物车，直接选择商品结算）
            carList = getCarList(productIds, user.getId(), distribution);
        } else { // 考虑区分加价够商品(即购物车结算商品)
            carList = ygShoppingCarService.findIsCheck(user.getId(), distribution);
        }
        if (CollectionUtils.isEmpty(carList)) {
            return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, null));
        }
        CarPricesResult carPrices = shoppingCarHandler.getCarPrices(carList, formId, null, salesPlatform);

        if (!carPrices.getUseCoupon() && cStatus.equals(CouponStatus.Usable)) {
            json = new JSONPObject(callback, Message.success(documentConstant.COUPON_IS_EMPTY, null));
        } else {
            BigDecimal couponValidPrice = carPrices.getProductPrice().subtract(carPrices.getNewCustomDisPrice()).subtract(carPrices.getPackDisPrice()).subtract(carPrices.getManJianPrice())
                    .subtract(carPrices.getSpecialPrice());
            if (couponValidPrice.compareTo(new BigDecimal(0)) < 0) {
                couponValidPrice = BigDecimal.ZERO;
            }
            Boolean onlySpecial = false;
            if (couponValidPrice.compareTo(zero) <= 0) {
                onlySpecial = true;
            }
            logger.info("findCouponListForPay.CarPricesResult = 【{}】,couponValidPrice=【{}】", JSON.toJSONString(carPrices), couponValidPrice);
            if (onlySpecial && cStatus.equals(CouponStatus.Usable)) {
                json = new JSONPObject(callback, Message.success(documentConstant.COUPON_IS_EMPTY, null));
            } else {
                List<YgCouponModel> model = couponService.findCouponListForPayV2(user.getId(), null, couponValidPrice, cStatus,
                        carPrices.getUseCoupon(), onlySpecial, carList, salesPlatform);
                json = new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, model));
            }
        }
        return json;
    }

    private List<YgShoppingCarModel> getCarList(String productIds, Long userId, boolean distribution) {
        List<BaseSkuInfo> skuInfoList = new ArrayList<>();
        for (String string : productIds.split(",")) {
            String productId = string.trim();
            if (StringUtils.isBlank(productId)) {
                continue;
            }
            List<YgSku> skuList = skuService.find(Long.valueOf(productId));
            if (CollectionUtils.isEmpty(skuList)) {
                continue;
            }
            skuInfoList.add(new BaseSkuInfo(skuList.get(0).getId(), 1L));
        }
        if (CollectionUtils.isEmpty(skuInfoList)) {
            return new ArrayList<>();
        }
        return ygShoppingCarService.findItemInfo(skuInfoList, userId, PromotionType.Ordinary, distribution);
    }


}
